package com.web.server;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.*;

@WebServlet(urlPatterns = "/againpass")
public class AgainPass extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        resp.setContentType("text/html;charset=UTF-8");
        String username = req.getParameter("username");
        String password = req.getParameter("oldPassword");
        String password1 = req.getParameter("newPassword");
        String againPass = req.getParameter("againPass");

        if (password1.equals(againPass)) {
            try {
                Class.forName("com.mysql.cj.jdbc.Driver");
                String url = "jdbc:mysql://127.0.0.1:3306/demo";
                Connection conn = DriverManager.getConnection(url, "root", "root");
                PreparedStatement stmt01 = conn.prepareStatement("select password from users where username=?");
                stmt01.setString(1, username);
                ResultSet rs = stmt01.executeQuery();
                if (rs.next()) {
                    String password2 = rs.getString("password");
                    if (password2.equals(password)) {
                        PreparedStatement stmt02 = conn.prepareStatement
                                ("update users set password=? where username=?");
                        stmt02.setString(1, againPass);
                        stmt02.setString(2, username);
                        int i = stmt02.executeUpdate();
                        if (i > 0) {
                            resp.getWriter().println("修改成功");
                        } else {
                            resp.getWriter().println("修改失败");
                        }
                    } else {
                        resp.getWriter().write("旧密码错误，修改失败");
                    }
                } else {
                    resp.getWriter().write("账号不存在");
                }


            } catch (ClassNotFoundException e) {
                throw new RuntimeException(e);
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        } else {
            resp.getWriter().write("两次密码不一致");
        }
    }
}
